﻿using System;
using System.Windows.Forms;
using Me.Amon.POS.M;
using Me.Amon.Util;
using Newtonsoft.Json;

namespace Me.Amon.POS.V
{
    public partial class WfEmp : Form
    {
        public WfEmp()
        {
            InitializeComponent();

            KeyPreview = true;
        }

        public MEmp SelectedEmp { get; set; }

        #region 事件处理
        private void WfEmp_Load(object sender, EventArgs e)
        {
            TbCode.SelectAll();
        }

        private void WfEmp_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                Close();
                return;
            }

            if (e.KeyCode == Keys.Up)
            {
                if (LbList.SelectedIndex > 0)
                {
                    LbList.SelectedIndex -= 1;
                }
                e.Handled = true;
                return;
            }
            if (e.KeyCode == Keys.Down)
            {
                if (LbList.SelectedIndex < LbList.Items.Count - 1)
                {
                    LbList.SelectedIndex += 1;
                }
                e.Handled = true;
                return;
            }
            if (e.KeyCode == Keys.Enter)
            {
                DoSelect();
                return;
            }
        }

        private void TbCode_TextChanged(object sender, EventArgs e)
        {
            LbList.Items.Clear();

            var key = TbCode.Text.Trim();
            if (string.IsNullOrWhiteSpace(key))
            {
                return;
            }

            var data = WebUtil.Select("/POS/Emp.ashx", key);
            LbList.Items.Clear();
            if (string.IsNullOrWhiteSpace(data))
            {
                return;
            }

            var emps = JsonConvert.DeserializeObject<MEmp[]>(data);
            if (emps.Length < 1)
            {
                return;
            }

            LbList.Items.AddRange(emps);
            LbList.SelectedIndex = 0;
        }

        private void LbList_DoubleClick(object sender, EventArgs e)
        {
            DoSelect();
        }
        #endregion

        private void DoSelect()
        {
            SelectedEmp = LbList.SelectedItem as MEmp;
            if (SelectedEmp != null)
            {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                Close();
            }
        }
    }
}
